package org.example.design.pattern.factorymethod.extend;

import java.lang.reflect.Constructor;

/**
 * @ClassName SingletonFactory
 * @Description 工厂模式实现单例
 **/
public class SingletonFactory {

    private static Singleton singleton;
    static {
        try {
            Class<?> clazz = Class.forName(Singleton.class.getName());
            // 获取无参构造，设置无参构造可以访问。
            Constructor<?> constructor = clazz.getDeclaredConstructor();
            constructor.setAccessible(true);
            singleton = (Singleton) constructor.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Singleton getSingleton() {
        return singleton;
    }
    /**
     * 构造参数私有化，无法从外部实例化对象
     */
    public static class Singleton {
        private Singleton() { }
    }
    public static void main(String[] args) {
        Singleton s = SingletonFactory.getSingleton();
        System.out.println(s.getClass());
    }
}
